package com.ctrip.corp.obt.shard.infrastructure.local;

import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.shard.configuration.DataShardProperties;
import com.ctrip.corp.obt.shard.constants.DbType;
import com.ctrip.corp.obt.shard.core.ShardDataSource;
import com.ctrip.corp.obt.shard.domain.gateway.DataShardSourceGateway;
import com.ctrip.corp.obt.shard.utils.JdbcUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用于未接入etcd，但需要额外配置数据源的环境
 *
 * @author x.shen
 * @since 2024/1/30
 */
@Slf4j
public class LocalDataShardSourceGateway implements DataShardSourceGateway {

    private final DataShardProperties dataShardProperties;

    public LocalDataShardSourceGateway(DataShardProperties dataShardProperties) {
        this.dataShardProperties = dataShardProperties;
    }

    @Override
    public Set<ShardDataSource> getAllSource() {
        return loadDataSource(dataShardProperties.getDataSources());
    }

    @Override
    public Set<ShardDataSource> getSourceByTenantIds(Set<String> tenantIds) {
        List<ShardDataSource> datasource = dataShardProperties.getDataSources().stream()
            .filter(source -> tenantIds.contains(source.getTenantId())).collect(Collectors.toList());
        return loadDataSource(datasource);
    }

    private Set<ShardDataSource> loadDataSource(List<ShardDataSource> localSources) {
        // 设置本地配置部分未配置信息
        for (ShardDataSource source : localSources) {
            source.setSource("local");
            if (CollectionUtils.isNotEmpty(source.getMetas())) {
                source.getMetas().forEach(meta -> meta.setDbType(JdbcUtils.getDbType(meta.getUrl()).getValue()));
            }
        }
        return new HashSet<>(localSources);
    }
}
